<?php

/**

 * 计划管理
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Home\Controller;

use Think\Controller;

class PlanController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        $this->limit = 10;

        //获取计划类型
//        $planType = M('plan_type')->order('type_no')->select();
        $this->webid = M('web')->where('webname="工作计划"')->getField('id');
    }

    //按权限获取部门 
    private function getPrivDept() {
        //个人
        $depts = [];

        //公司领导
        $leader = $this->isLeader();
        if ($leader) {
            //除公司领导外所有部门
            $depts = M('department')->select();
        }

        //部门领导
        $deptLeader = $this->isDeptLeader();
        if ($deptLeader) {
            //本部门
            $depts[] = M('department')->where('dept_id=' . session('dept_id'))->find();
        }

        return $depts;
    }

    //判断公司领导
    private function isLeader() {
        $deptId = M('department')->where('dept_name="公司领导"')->getField('dept_id');
        if (session('dept_id') == $deptId) {
            return true;
        } else {
            return false;
        }
    }

    //判断部门领导
    private function isDeptLeader() {
        $map['priv_no'] = array('between', [30, 40]);
        $privIds = M('user_priv')->where($map)->getField('user_priv', true);

        $user = M('user')->where('user_id="' . session('user_id') . '"')->find();
        $user_priv = $user['user_priv'];
        if ($user['user_priv_other']) {
            $other = explode(',', trim($user['user_priv_other'], ','));
            array_push($other, $user_priv);
        }

        $flag = false;
        foreach ($other as $key => $row) {
            if (in_array($row, $privIds)) {
                $flag = true;
            }
            if ($user['user_id'] == 'zhangjing') {
                $flag = true;
            }
        }
        return $flag;
    }

    /*
     * 计算计划总进度并修改总进度字段
     * 原先通过判断负责人和参与人进度百分比计算总进度
     * 2018-1-11改为只判断负责人，负责人百分比为100时，总进度100，状态为1，否则0
     * @author   zhangyingheng
     */

    private function savePlanPercent() {
        //获取所有计划
        $plans = M('work_plan')->where('sms_flag = 0')->select();
        $now = date('Y-m-d');
        foreach ($plans as $key => $row) {
            if ($row['total_percent'] == 100 || ($row['end_date'] < $now && ($row['end_date'] !== '0000-00-00'))) {
                //改状态sms_flag=1（总进度为100时或者结束日期存在并且小于当前时间时改为结束状态）
                $sData['sms_flag'] = 1;
                M('work_plan')->where('plan_id=' . $row['plan_id'])->save($sData);
            } else {
                $map['plan_id'] = $row['plan_id'];
                if (getPlanMode($row['type']) == 0) {
                    //日计划
                    $count = count(explode(',', rtrim($row['executor'], ',')));
                    if ($count > 1) {
                        $write = explode(',', rtrim($row['executor'], ','));
                        $totalPercent = 0;
                        foreach ($write as $k_w => $k_v) {
                            $map['writer'] = array('like', '%' . $k_v . '%');
                            $totalPercent += M('work_detail')->where($map)->max('percent');
                        }
                        $percer = $totalPercent / (100 * $count) * 100;
                    } else {
                        $map['writer'] = rtrim($row['executor'], ',');
                        $percer = M('work_detail')->where($map)->max('percent');
                    }
                } else {
                    //详细
                    $count = count(explode(',', rtrim($row['manager'], ',')));
                    if ($count > 1) {
                        $write = explode(',', rtrim($row['manager'], ','));
                        $totalPercent = 0;
                        foreach ($write as $k_w => $k_v) {
                            $map['writer'] = array('like', '%' . $k_v . '%');
                            $totalPercent += M('work_detail')->where($map)->max('percent');
                        }
                        $percer = $totalPercent / (100 * $count) * 100;
                    } else {
                        $map['writer'] = rtrim($row['manager'], ',');
                        $percer = M('work_detail')->where($map)->max('percent');
                    }
                }

                if ($percer >= 100) {
                    $sData['sms_flag'] = 1;
                    $sData['total_percent'] = 100;
                } else {
                    $sData['sms_flag'] = 0;
                    $sData['total_percent'] = $percer ? $percer : 0;
                }
                M('work_plan')->where('plan_id=' . $row['plan_id'])->save($sData);
            }
        }
    }

    //首页
    public function index() {
        $this->savePlanPercent();
        //获取相应部门
        $this->depts = $this->getPrivDept();

        //搜索
        if (isset($_GET['pType']) && I('pType')) {
            $map['type'] = I('pType');
            $this->pType = I('pType');
        }
        if (isset($_GET['child_type']) && I('child_type')) {
            $map['child_type'] = I('child_type');
            $this->pFlag = I('child_type');
        }
        if (isset($_GET['level']) && I('level')) {
            $map['level'] = I('level');
            $this->level = I('level');
        }
        if (isset($_GET['sms_flag']) && I('sms_flag') > 0) {
            if (I('sms_flag') !== '' && I('sms_flag') != '2') {//by qiao update 2018/07/05 从考勤那边链接过来 2代表全部
                $map['sms_flag'] = I('sms_flag');
            } else {
                unset($map['sms_flag']);
            }
            $this->smsFlag = I('sms_flag');
        } else {
            $map['sms_flag'] = 0;   //默认列表中取进行中的计划
        }
        if (isset($_GET['plan_name']) && I('plan_name')) {
            $map['name'] = array('like', '%' . I('plan_name') . '%');
            $this->planName = I('plan_name');
        }
        if (isset($_GET['start']) && I('start') && !isset($_GET['user_id'])) {  //by qiao update 2018/07/05 从考勤那边链接过来
            $map['_string'] = ' begin_date <= "' . I('start') . '" and END_DATE >= "' . I('end') . '"';
            $this->start = I('start');
            $this->end = I('end');
        }elseif(isset($_GET['user_id'])){//by qiao update 2018/07/05 从考勤那边链接过来
            $map['_string'] = ' begin_date like "%'.$_GET['date'].'%"';
        }

        //和我相关包含部门的计划
        if (isset($_GET['dept']) && I('dept')) {
            $where['_string'] = 'TO_ID like "%' . session('dept_id') . '%" or TO_ID = ""';
        }

        //判断是否是领导
        $isLeader = false;
        if ($this->isLeader() == true) {
            $isLeader = true;
            $ids = M('department')->where('dept_name != "公司领导"')->getField('dept_id', true);
            $dMap['to_id'] = array('in', $ids);
        }
        if ($this->isDeptLeader() == true) {
            $isLeader = true;
            $deptId = I('to_id') ? I('to_id') : session('dept_id');
            $dMap['to_id'] = $deptId;
        }

        $this->isLeader = $isLeader;

        //部门
        if (isset($_GET['to_id']) && I('to_id')) {
//            $deptId = I('to_id');
            $users = M('user')->where('dept_id = '.I('to_id'))->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }
            foreach ($users as $key => $value) {
                $sql .= ' executor like "%' . $value . '%" or manager like "%' . $value . '%" or participator like "%' . $value . '%" or';
                $where['_string'] = rtrim($sql, ' or');
                $map['_complex'] = $where;
            }
            $this->deptName = I('to_id') ? I('to_id') : '';
        } elseif (isset($_GET['user_id'])) {    //by qiao update 2018/07/05 从考勤那边链接过来
            $where['executor'] = array('like', '%' . $_GET['user_id'] . '%');
            $where['manager'] = array('like', '%' . $_GET['user_id'] . '%');
            $where['participator'] = array('like', '%' . $_GET['user_id'] . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        } else {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['manager'] = array('like', '%' . session('user_id') . '%');
            $where['participator'] = array('like', '%' . session('user_id') . '%');
            $where['creator'] = session('user_id');
            $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
            $where['opinion_leader'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }

        //我关注的计划
        if (isset($_GET['follow']) && I('follow')) {
            unset($map['_complex']);
            unset($map['sms_flag']);
            $map['follow_user'] = array('like', '%' . session('user_id') . '%');
        }

        //分页
        $p = I('get.p', 1, 'intval');
        $this->p = $p;
        $limit = 15;
        $count = M('work_plan')->where($map)->count();
        $this->count = $count;
        $this->page = $this->pageLists($count, $limit);

        $data = M('work_plan')->where($map)->order('begin_date desc,level desc')->page($p, $limit)->select();

        $num = ($p - 1) * $limit + 1;
        foreach ($data as $key => $row) {
//            if ($row['type'] == 1 && $row['is_mobile'] == 1) {
//                $data[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr($row['content'], 0, 16) . '（' . getPlanFlagName($row['flag']) . '）</font>';
//            } else if ($row['type'] == 1) {
//                $data[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr(strip_tags($row['name']), 0, 16) . '（' . getPlanFlagName($row['flag']) . '）</font>';
//            }
            $data[$key]['num'] = $num++;
            //日计划标题加样式
            if ($row['type'] == 1 && $row['is_mobile'] == 1) {
                $content = strlen($row['content']) > 60 ? msubstr($row['content'], 0, 20) : $row['content'];
                $data[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . $content . '（' . getPlanFlagName($row['flag']) . '）</font>';
                $data[$key]['fullName'] = $row['content'];
            } else if ($row['type'] == 1) {
                $data[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . strip_tags($row['content']) . '（' . getPlanFlagName($row['flag']) . '）</font>';
                $data[$key]['fullName'] = strip_tags($row['content']);
            }
            
            if($row['type'] !== 1){
                $data[$key]['fullName'] = $row['name'];
            }

            $data[$key]['manager'] = getChineseName(rtrim($row['manager'], ','));
            if ($row['creator'] == session('user_id')) {
                $data[$key]['is_creator'] = 1;
            }

            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $data[$key]['noRead'] = 1;
            } else {
                $data[$key]['noRead'] = 0;
            }

            if ($row['type'] == 1) {
                if ($row['executor'] == session('user_id')) {
                    $data[$key]['is_manager'] = 1;
                }
            } else {
                if ($row['manager'] == session('user_id')) {
                    $data[$key]['is_manager'] = 1;
                }
            }

            //显示二级分类type_name
            if ($row['child_type']) {
                $data[$key]['child_type'] = M('plan_type')->where('type_id=' . $row['child_type'])->getField('type_name');
            } else {
                $data[$key]['child_type'] = '';
            }

            //是否关注
            if ($row['follow_user']) {
                $fusers = explode(',', rtrim($row['follow_user'], ','));
                if (in_array(session('user_id'), $fusers)) {
                    $data[$key]['follow'] = 1;
                } else {
                    $data[$key]['follow'] = 0;
                }
            } else {
                $data[$key]['follow'] = 0;
            }
            
            $data[$key]['sms_flag'] = I('sms_flag');
        }
//          print_r($data);
        //加条件参数  5:没有条件
        if (isset($_GET['type'])) {
            $this->condition = I('type');
        } else {
            $this->condition = I('type') ? I('type') : 5;
        }

        //获取新建计划的backmenu.id
        $this->mid = M('backmenu')->where('name="新建计划"')->getField('id');
        $this->data = $data;
        $this->title = '计划列表';

        //获取计划类型
        unset($map);
//        $map['_string'] = 'pid = 0 or (pid != 0 and user_id = "' . session('user_id') . '")';
        $map['pid'] = 0;
        $this->planType = M('plan_type')->where($map)->order('type_no')->select();
//        $this->planType = getTree($data, 0);
        //获取计划标记;
        $map['pid'] = array('neq',0);
        $map['user_id'] = session('user_id');
        $this->planFlag = M('plan_type')->where($map)->order('type_no')->select();
        
        $this->display();
    }

    //首页
    public function lists() {
        //获取相应部门
        $this->depts = $this->getPrivDept();

        //搜索
        if (isset($_GET['pType']) && I('pType')) {
            $map['_string'] = ' type = ' . I('pType') . ' or child_type = ' . I('pType');
            $this->pType = I('pType');
        }
        if (isset($_GET['level']) && I('level')) {
            $map['level'] = I('level');
            $this->level = I('level');
        }
        if (isset($_GET['sms_flag']) && I('sms_flag') > 0) {
            if (I('sms_flag') !== '') {
                $map['sms_flag'] = I('sms_flag');
            } else {
                unset($map['sms_flag']);
            }
            $this->smsFlag = I('sms_flag');
        } else {
            $map['sms_flag'] = 0;   //默认列表中取进行中的计划
        }
        if (isset($_GET['plan_name']) && I('plan_name')) {
            $map['name'] = array('like', '%' . I('plan_name') . '%');
            $this->planName = I('plan_name');
        }
        if (isset($_GET['start']) && I('start')) {
            $map['_string'] = ' begin_date >= "' . I('start') . '" and end_date <= "' . I('end') . '"';
            $this->start = I('start');
            $this->end = I('end');
        }

        //和我相关包含部门的计划
        if (isset($_GET['dept'])) {
            $where['_string'] = 'to_id like "%' . session('dept_id') . '%" or to_id = ""';
            $this->adept = I('dept');
        }


        //判断是否是领导
        $isLeader = false;
        if ($this->isLeader() == true) {
            $isLeader = true;
            $ids = M('department')->where('dept_name != "公司领导"')->getField('dept_id', true);
            $dMap['to_id'] = array('in', $ids);
        }
        if ($this->isDeptLeader() == true) {
            $isLeader = true;
            $deptId = I('to_id') ? I('to_id') : session('dept_id');
            $dMap['to_id'] = $deptId;
        }

        $this->isLeader = $isLeader;

        //部门
        if (isset($_GET['to_id'])) {
            $users = M('user')->where($dMap)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }
            foreach ($users as $key => $value) {
                $sql .= ' executor like "%' . $value . '%" or manager like "%' . $value . '%" or participator like "%' . $value . '%" or';
                $where['_string'] = rtrim($sql, ' or');
                $map['_complex'] = $where;
            }
            $this->deptName = I('to_id') ? I('to_id') : '';
        } else {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['manager'] = array('like', '%' . session('user_id') . '%');
            $where['participator'] = array('like', '%' . session('user_id') . '%');
            $where['creator'] = session('user_id');
            $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
            $where['opinion_leader'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }

        //我关注的计划
        if (isset($_GET['follow']) && I('follow')) {
            unset($map);
            $map['follow_user'] = array('like', '%' . session('user_id') . '%');
            $this->follow = I('follow');
        }

        $data = M('work_plan')->where($map)->order('begin_date desc,level desc')->select();

        $p = I('get.p', 1, 'intval');
        $num = ($p - 1) * $limit + 1;
        foreach ($data as $key => $row) {
            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $datas[$key] = $row;
                $datas[$key]['noRead'] = 1;
            }
        }

        foreach ($datas as $key => $row) {
            $datas[$key]['num'] = $num++;
            $datas[$key]['ajaxlist'] = 1;

            //日计划标题加样式
            if ($row['type'] == 1 && $row['is_mobile'] == 1) {
                $content = strlen($row['content']) > 60 ? msubstr($row['content'], 0, 20) : $row['content'];
                $data[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . $content . '（' . getPlanFlagName($row['flag']) . '）</font>';
                $data[$key]['fullName'] = $row['content'];
            } else if ($row['type'] == 1) {
                $data[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . strip_tags($row['content']) . '（' . getPlanFlagName($row['flag']) . '）</font>';
                $data[$key]['fullName'] = strip_tags($row['content']);
            }
            
            if($row['type'] !== 1){
                $data[$key]['fullName'] = $row['name'];
            }

            $datas[$key]['manager'] = getChineseName(rtrim($row['manager'], ','));
            if ($row['creator'] == session('user_id')) {
                $datas[$key]['is_creator'] = 1;
            }

            if ($row['type'] == 1) {
                if ($row['executor'] == session('user_id')) {
                    $datas[$key]['is_manager'] = 1;
                }
            } else {
                if ($row['manager'] == session('user_id')) {
                    $datas[$key]['is_manager'] = 1;
                }
            }
            //显示二级分类type_name
            if ($row['child_type']) {
                $datas[$key]['child_type'] = M('plan_type')->where('type_id=' . $row['child_type'])->getField('type_name');
            } else {
                $datas[$key]['child_type'] = '';
            }

            //是否关注
            if ($row['follow_user']) {
                $fusers = explode(',', rtrim($row['follow_user'], ','));
                if (in_array(session('user_id'), $fusers)) {
                    $datas[$key]['follow'] = 1;
                } else {
                    $datas[$key]['follow'] = 0;
                }
            } else {
                $datas[$key]['follow'] = 0;
            }
        }

        $newData = array_slice($datas, 0, 15);

        $this->count = count($datas);

        $page = new \Think\MyPage(count($datas), 15);
        $pages['list'] = $list;
        $pages['first'] = $page->first();
        $pages['prev'] = $page->prev();
        $pages['next'] = $page->next();
        $pages['last'] = $page->last();
        $pages['curr'] = $p;
        $pages['page'] = explode(' ', $page->pageList_ajax());
        $this->ajaxpages = $pages;

//        print_r($datas);
        //加条件参数  5:没有条件
        if (isset($_GET['type'])) {
            $this->condition = I('type');
        } else {
            $this->condition = I('type') ? I('type') : 5;
        }

        //获取新建计划的backmenu.id
        $this->mid = M('backmenu')->where('name="新建计划"')->getField('id');
        $this->data = $newData;
        $this->title = '计划列表';

        //获取计划类型
        unset($map);
        $map['_string'] = 'pid = 0 or (pid != 0 and user_id = "' . session('user_id') . '")';
        $data = M('plan_type')->where($map)->order('type_no')->select();
        $this->planType = getTree($data, 0);

        $this->atype = I('type');
        $this->smsFlag = I('sms_flag');

        $this->display();
    }

    //ajax分页显示计划列表
    public function getPlanAjaxPage() {
        //获取相应部门
        $this->depts = $this->getPrivDept();

        //搜索
        if (isset($_GET['pType']) && I('pType')) {
            $map['_string'] = ' type = ' . I('pType') . ' or child_type = ' . I('pType');
            $this->pType = I('pType');
        }
        if (isset($_GET['level']) && I('level')) {
            $map['level'] = I('level');
            $this->level = I('level');
        }
        if (isset($_GET['sms_flag'])) {
            if (I('sms_flag') !== '') {
                $map['sms_flag'] = I('sms_flag') == 1 ? 0 : 1;
            } else {
                unset($map['sms_flag']);
            }
            $this->smsFlag = I('sms_flag');
        } else {
            $map['sms_flag'] = 0;   //默认列表中取进行中的计划
        }
        if (isset($_GET['plan_name']) && I('plan_name')) {
            $map['name'] = array('like', '%' . I('plan_name') . '%');
            $this->planName = I('plan_name');
        }
        if (isset($_GET['start']) && I('start')) {
            $map['_string'] = ' begin_date >= "' . I('start') . '" and end_date <= "' . I('end') . '"';
            $this->start = I('start');
            $this->end = I('end');
        }

        //和我相关包含部门的计划
        if (isset($_GET['dept'])) {
            $where['_string'] = 'to_id like "%' . session('dept_id') . '%" or to_id = ""';
            $this->adept = I('dept');
        }


        //判断是否是领导
        $isLeader = false;
        if ($this->isLeader() == true) {
            $isLeader = true;
            $ids = M('department')->where('dept_name != "公司领导"')->getField('dept_id', true);
            $dMap['to_id'] = array('in', $ids);
        }
        if ($this->isDeptLeader() == true) {
            $isLeader = true;
            $deptId = I('to_id') ? I('to_id') : session('dept_id');
            $dMap['to_id'] = $deptId;
        }

        $this->isLeader = $isLeader;

        //部门
        if (isset($_GET['to_id'])) {
            $users = M('user')->where($dMap)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }
            foreach ($users as $key => $value) {
                $sql .= ' executor like "%' . $value . '%" or manager like "%' . $value . '%" or participator like "%' . $value . '%" or';
                $where['_string'] = rtrim($sql, ' or');
                $map['_complex'] = $where;
            }
            $this->deptName = I('to_id') ? I('to_id') : '';
        } else {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['manager'] = array('like', '%' . session('user_id') . '%');
            $where['participator'] = array('like', '%' . session('user_id') . '%');
            $where['creator'] = session('user_id');
            $where['to_person_id'] = array('like', '%' . session('user_id') . '%');
            $where['opinion_leader'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }

        //我关注的计划
        if (isset($_GET['follow']) && I('follow')) {
            unset($map);
            $map['follow_user'] = array('like', '%' . session('user_id') . '%');
            $this->follow = I('follow');
        }

        $data = M('work_plan')->where($map)->order('begin_date desc,level desc')->select();

        foreach ($data as $key => $row) {
            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $datas[$key] = $row;
                $datas[$key]['noRead'] = 1;
            }
        }

        $num = 1;
        foreach ($datas as $key => $row) {
            $datas[$key]['num'] = $num++;
            $datas[$key]['ajaxlist'] = 1;

            //日计划标题加样式
            if ($row['type'] == 1 && $row['is_mobile'] == 1) {
                $content = strlen($row['content']) > 60 ? msubstr($row['content'], 0, 20) : $row['content'];
                $datas[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . $content . '（' . getPlanFlagName($row['flag']) . '）</font>';
            } else if ($row['type'] == 1) {
                $datas[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . strip_tags($row['content']) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            }
            $datas[$key]['manager'] = getChineseName(rtrim($row['manager'], ','));
            if ($row['creator'] == session('user_id')) {
                $datas[$key]['is_creator'] = 1;
            }

            if ($row['type'] == 1) {
                if ($row['executor'] == session('user_id')) {
                    $datas[$key]['is_manager'] = 1;
                }
            } else {
                if ($row['manager'] == session('user_id')) {
                    $datas[$key]['is_manager'] = 1;
                }
            }
            //显示二级分类type_name
            if ($row['child_type']) {
                $datas[$key]['child_type'] = M('plan_type')->where('type_id=' . $row['child_type'])->getField('type_name');
            } else {
                $datas[$key]['child_type'] = '';
            }

            //获取日计划执行人
            if ($row['executor']) {
                $datas[$key]['executor'] = getMoreUsername($row['executor']);
            }

            //是否关注
            if ($row['follow_user']) {
                $fusers = explode(',', rtrim($row['follow_user'], ','));
                if (in_array(session('user_id'), $fusers)) {
                    $datas[$key]['follow'] = 1;
                } else {
                    $datas[$key]['follow'] = 0;
                }
            } else {
                $datas[$key]['follow'] = 0;
            }
        }

        $p = I('get.p');
        $limit = 15;
        $start = $limit * ($p - 1);

        $newData = array_slice($datas, $start, 15);

        $page = new \Think\MyPage(count($datas), $limit);
        $datas['list'] = $newData;
        $datas['first'] = $page->first();
        $datas['prev'] = $page->prev();
        $datas['next'] = $page->next();
        $datas['last'] = $page->last();
        $datas['curr'] = I('get.p');
        $datas['page'] = explode(' ', $page->pageList_ajax());

        $this->ajaxReturn($datas);
    }

    //添加计划
    public function save() {
        if (IS_AJAX) {
            $data = I('post.');

            //添加子分类
            if ($data['add_type']) {
                $tdata['type_name'] = $data['add_type'];
                $tdata['type_no'] = 10;
                $tdata['mode'] = 1;
                $tdata['pid'] = $data['type'];
                $tdata['user_id'] = session('user_id');
                $pdata['child_type'] = M('plan_type')->add($tdata);
            } else {
                $pdata['child_type'] = $data['child_type'];
            }

            //添加work_plan表
            //判断是否为日计划
            if (getPlanMode($data['type']) == 0) {
                $pdata['name'] = $data['cont'];
                $pdata['content'] = $data['cont'];
                $pdata['executor'] = implode(',', $data['executor']);
                $pdata['flag'] = $data['flag'];
                $pdata['level'] = $data['s_level'];
                $pdata['cycle'] = $data['s_cycle'];
                $pdata['BEGIN_DATE'] = $data['begin_date'] ? $data['begin_date'] : date('Y-m-d');
                $pdata['END_DATE'] = $data['end_date'] ? $data['end_date'] : '0000-00-00';
                $pdata['attach_type'] = $data['s_attach_type'];
                $pdata['is_mobile'] = 1;
            } else {
                $pdata['name'] = $data['name'];
                $pdata['content'] = $data['content'];
                $pdata['manager'] = implode(',', $data['manager']);
                $pdata['participator'] = implode(',', $data['participator']);
                $pdata['level'] = $data['level'];
                $pdata['cycle'] = $data['cycle'];
                $pdata['BEGIN_DATE'] = $data['begin_date'] ? $data['begin_date'] : date('Y-m-d');
                $pdata['END_DATE'] = $data['end_date'] ? $data['end_date'] : '0000-00-00';
                $pdata['attach_type'] = $data['attach_type'];
            }
            $pdata['type'] = $data['type'];
            $pdata['to_id'] = implode(',', $data['dept_ids']);
            $pdata['remark'] = $data['remark'];
            $pdata['to_person_id'] = implode(',', $data['to_person_id']);
            $pdata['publish'] = 1;
            $pdata['opinion_leader'] = implode(',', $data['opinion_leader']);
            $pdata['sms_flag'] = 0;
            $pdata['uploads'] = $data['uploads'];
            $pdata['uploads_url'] = $data['uploads_url'];

            if ($data['plan_id']) {
                $row = M('work_plan')->where('plan_id=' . $data['plan_id'])->find();
                $pdata['attach_type'] = $row['attach_type'];
                $res = M('work_plan')->where('plan_id=' . $data['plan_id'])->save($pdata);
            } else {
                $pdata['creator'] = session('user_id');
                $pdata['create_date'] = date('Y-m-d');
                $res = M('work_plan')->add($pdata);
            }

            if ($res !== false) {
                $return['info'] = '操作成功';
                $return['url'] = U('index');
            } else {
                $return['info'] = '操作失败';
            }
            $this->ajaxReturn($return);
        }

        if (I('id')) {
            $info = M('work_plan')->where('plan_id=' . I('id'))->find();
//            $info['manager'] = rtrim($info['manager'], ',');
            $info['manager'] = array_unique($info['manager'] ? explode(',', rtrim($info['manager'], ',')) : '');
            $info['execs'] = array_unique($info['executor'] ? explode(',', rtrim($info['executor'], ',')) : '');
            $info['parts'] = array_unique($info['participator'] ? explode(',', rtrim($info['participator'], ',')) : '');    //参与人（执行人）
            $info['depts'] = $info['to_id'] ? explode(',', rtrim($info['to_id'], ',')) : '';   //开放部门
            $info['persons'] = $info['to_person_id'] ? explode(',', rtrim($info['to_person_id'], ',')) : '';  //开放人员
            $info['leaders'] = $info['opinion_leader'] ? explode(',', rtrim($info['opinion_leader'], ',')) : '';  //批注领导
            //获取PC端文件
            if ($info['attachment_name']) {
                $uploads = downloadFile($info['attachment_id'], $info['attachment_name'], 'work_plan', $info['uploads'], $info['uploads_url']);
            }
            if ($info['uploads_url']) {
                $names = explode(';', rtrim($info['uploads'], ';'));
                $urls = explode(';', rtrim($info['uploads_url'], ';'));
                for ($i = 0; $i < count($urls); $i++) {
                    $tmpArr = [];
                    if ($urls[$i]) {
                        if ($uploads) {
                            $tmpArr['name'] = $names[$i];
                            $tmpArr['url'] = $urls[$i];
                            array_push($uploads, $tmpArr);
                        } else {
                            $uploads[$i]['name'] = $names[$i];
                            $uploads[$i]['url'] = $urls[$i];
                        }
                    }
                }
            }
            $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
            foreach ($uploads as $key => $row) {
                $ext = end(explode('.', $row['name']));
                $uploads[$key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
                $uploads[0]['uploadsName'] = $info['uploads'];
                $uploads[0]['uploadsUrl'] = $info['uploads_url'];
            }

            //计划中的附件
            $this->uploads = $uploads;
            $this->info = $info;
            $this->type = I('type');
        }

        //接收返回参数
        $this->params = I('get.');

        //获取计划类型
        $this->planType = M('plan_type')->where('pid = 0')->order('type_no')->select();
        
        //获取计划标记;
        $map['pid'] = array('neq',0);
        $map['user_id'] = session('user_id');
        $this->planFlag = M('plan_type')->where($map)->order('type_no')->select();

        $this->id = I('id');
        $this->display();
    }

    //获取子分类数据
    public function getChildType() {
        $id = I('id');
        $map['pid'] = $id;
        $map['user_id'] = session('user_id');
        $data = M('plan_type')->where($map)->select();
        $this->ajaxReturn($data);
    }

    //删除计划
    public function delete() {
        $plan_id = I('id');
        $info = M('work_plan')->where('plan_id=' . $plan_id)->find();
        if ($info['attachment_name']) {
            $pcfiles = downloadFile($info['attachment_id'], $info['attachment_name'], 'work_plan');
//            foreach($pcfiles as $row){
//                @unlink($row['url']);
//            }
        }
        if ($info['uploads_url']) {
            $files = explode(';', $info['uploads_url']);
            foreach ($files as $row) {
                @unlink('.' . $row);
            }
        }

        $details = M('work_detail')->where('plan_id=' . $plan_id)->select();
        if ($details) {
            foreach ($details as $key => $row) {
                if ($row['attachment_name']) {
                    $pcfiles = downloadFile($info['attachment_id'], $info['attachment_name'], 'work_plan');
//                    foreach ($pcfiles as $file) {
//                        @unlink($file['url']);
//                    }
                }
                if ($row['uploads_url']) {
                    $files = explode(';', $row['uploads_url']);
                    foreach ($files as $file) {
                        @unlink('.' . $file);
                    }
                }
            }
        }

        //删除
        $resPlan = M('work_plan')->where('plan_id=' . $plan_id)->delete();
        $resDetail = M('work_detail')->where('plan_id=' . $plan_id)->delete();

        if ($resPlan !== false) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //结束或开始计划
    public function theend() {
        $type = I('type');
        $plan_id = I('id');
        if ($type == 1) { //结束计划
            $data['sms_flag'] = 1;
        } else {  //开始计划
            $data['sms_flag'] = 0;
        }
        $res = M('work_plan')->where('plan_id=' . $plan_id)->save($data);
        $this->ajaxReturn($res !== false ? 1 : 0);
    }

    public function upload() {
        $this->upfile('./Public/Uploads/plan/');
    }

    //详情页
    public function show() {
        if(IS_AJAX){
            $data = I('post.');
            
            if ($data['add_type']) {
                $tdata['type_name'] = $data['add_type'];
                $tdata['type_no'] = 10;
                $tdata['mode'] = 1;
                $tdata['pid'] = 1;  //改为标签，不需要pid，默认为1
                $tdata['user_id'] = session('user_id');
                $pdata['child_type'] = M('plan_type')->add($tdata);
            } else {
                $pdata['child_type'] = $data['child_type'];
            }
            $res = M('work_plan')->where('plan_id='.$data['id'])->save($pdata);
            $return['info'] = $res !== false ? '添加标记成功':'添加标记失败';
            $return['reload'] = 1;
            $this->ajaxReturn($return);
        }
        
        //获取计划标记;
        $map['pid'] = array('neq',0);
        $map['user_id'] = session('user_id');
        $this->planFlag = M('plan_type')->where($map)->order('type_no')->select();
        
        $id = I('id');
        $map['plan_id'] = $id;
        $info = M('work_plan')->where($map)->find();

        //增加已读标记
        if ($info['reader']) {
            $reader = $info['reader'] . ',' . session('user_id');
            $reader = array_unique(explode(',', $reader));
            $rData['reader'] = implode(',', $reader);
        } else {
            $rData['reader'] = session('user_id');
        }

        $info['name'] = strlen($info['name']) > 60 ? msubstr($info['name'], 0, 20) : $info['name'];

        if ($info['executor']) {
            $info['names'] = getMoreUsername($info['executor']);
        } else {
            $info['names'] = getMoreUsername($info['participator']);
        }

        M('work_plan')->where($map)->save($rData);

        /*
         * 进度和批注按时间顺序分成两个数组 2018-6-19 zyh
         */
        //进度
        $map['type_flag'] = 0;
        $info['detail'] = M('work_detail')->where($map)->order('write_time DESC')->select();

        if ($info['detail']) {
            foreach ($info['detail'] as $key => $row) {
                $info['detail'][$key]['formatTime'] = strtotime($row['write_time']);
                $info['detail'][$key]['self'] = session('user_id');     //本人
                //判断当前进度中是否有附件
                if ($row['attachment_id'] || $row['uploads_url']) {
                    $info['detail'][$key]['file'] = 1;
                    $dUploads = downloadFile($row['attachment_id'], $row['attachment_name'], 'work_plan', $row['uploads'], $row['uploads_url']);
                    $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
                    foreach ($dUploads as $d_key => $d_row) {
                        $ext = end(explode('.', $d_row['name']));
                        $dUploads[$d_key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
                    }
                    $info['detail'][$key]['uploads'] = $dUploads;
                }
            }
        }

        //批注
        $map['type_flag'] = 1;
        $info['comment'] = M('work_detail')->where($map)->order('write_time DESC')->select();

        //获取当前计划中参与人和负责人的进度
        $manager = explode(',', rtrim($info['manager'], ','));
        $participator = explode(',', rtrim($info['participator'], ','));
        $executor = explode(',', rtrim($info['executor'], ','));
        $users = array_merge($manager, $participator, $executor);
        $users = array_unique($users);

        $dMap['plan_id'] = $id;
        foreach ($users as $key => $row) {
            if ($row['user']) {
                $progress[$key]['user'] = $row;
                $dMap['writer'] = $row;
                $percent = M('work_detail')->where($dMap)->max('percent');
                if (!$percent) {
                    $progress[$key]['percent'] = '0%';
                } else {
                    if ($percent > 100) {
                        $percent = 100;
                    }
                    $progress[$key]['percent'] = $percent . '%';
                }
            }
        }

        //总进度
        $num = 0;
        foreach ($progress as $key => $row) {
            $num += $row['percent'];
        }
        $total = $num / (count($progress) * 100);

        if ($total > 100) {
            $total = 100;
        } else {
            $total = intval($total * 100);
        }
        $this->total = $total;
        $this->plan = $info;
        $this->sums = $progress;
//print_r($info);
        //获取PC端文件
        $ispc = 0;
        if ($info['attachment_name']) {
            $uploads = downloadFile($info['attachment_id'], $info['attachment_name'], 'work_plan', $info['uploads'], $info['uploads_url']);
            $ispc = 1;
        }
        if ($info['uploads_url']) {
            $names = explode(';', rtrim($info['uploads'], ';'));
            $urls = explode(';', rtrim($info['uploads_url'], ';'));
            for ($i = 0; $i < count($urls); $i++) {
                $tmpArr = [];
                if ($urls[$i]) {
                    if ($uploads) {
                        $tmpArr[$i]['name'] = $names[$i];
                        $tmpArr[$i]['url'] = $urls[$i];
                        array_push($uploads, $tmpArr);
                    } else {
                        $uploads[$i]['name'] = $names[$i];
                        $uploads[$i]['url'] = $urls[$i];
                    }
                }
            }
        }
        $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
        foreach ($uploads as $key => $row) {
            $ext = end(explode('.', $row['name']));
            $uploads[$key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
        }

        //判断用户是否有写进度日志的权限
        if (in_array(session('user_id'), $users)) {
            $is_write = 1;
        } else {
            $is_write = 0;
        }
        //判断用户是否有编辑进度日志的权限
        $diaryCount = M('work_detail')->where('plan_id = ' . $id . ' and writer like "%' . session('user_id') . '%"')->count();
        if ($diaryCount) {
            $is_edit = 1;
        } else {
            $is_edit = 0;
        }
        $this->is_write = $is_write;
        $this->is_edit = $is_edit;
        //计划中的附件
        $this->uploads = $uploads;

        //获取条件参数
        $type = I('get.type') ? I('get.type') : 0;
        $this->type = $type;

        if ($type) {
            if ($type == 5) {
                $this->path = '/index.php/Home/Plan/index';
            } else {
                $tMap['param'] = 'type=' . $type;
                $tMap['pid'] = M('backmenu')->where('name="计划管理"')->getField('id');
                $url = M('backmenu')->where($tMap)->getField('url');
                $this->path = '/index.php/Home/' . $url . '&type=' . $type;
            }
        }
//        echo $this->path;

        $this->pType = I('pType') ? I('pType') : '';
        $this->level = I('level') ? I('level') : '';
        $this->smsFlag = I('sms_flag');
        $this->planName = I('plan_name') ? I('plan_name') : '';
        $this->start = I('start') ? I('start') : '';
        $this->end = I('end') ? I('end') : '';
        $this->deptName = I('to_id') ? I('to_id') : '';
        $this->dept = I('dept') ? I('dept') : '';
        $this->ajaxlist = I('ajaxlist') ? I('ajaxlist') : 0;
        $this->follow = I('follow') ? I('follow') : '';

        $this->display();
    }

    /*
     * 计算单个计划总进度
     * @author   zhangyingheng
     */

    private function saveOnePercent($plan_id) {
        $row = M('work_plan')->where('plan_id=' . $plan_id)->find();

        $map['plan_id'] = $row['plan_id'];
        if (getPlanMode($row['type']) == 0) {
            //日计划
            $count = count(explode(',', rtrim($row['executor'], ',')));
            if ($count > 1) {
                $write = explode(',', rtrim($row['executor'], ','));
                $totalPercent = 0;
                foreach ($write as $k_w => $k_v) {
                    $map['writer'] = array('like', '%' . $k_v . '%');
                    $totalPercent += M('work_detail')->where($map)->max('percent');
                }
                $percer = $totalPercent / (100 * $count) * 100;
            } else {
                $map['writer'] = rtrim($row['executor'], ',');
                $percer = M('work_detail')->where($map)->max('percent');
            }
        } else {
            //详细
            $count = count(explode(',', rtrim($row['manager'], ',')));

            if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1 && $count > 1) {
                $write = explode(',', rtrim($row['manager'], ','));
                $totalPercent = 0;
                foreach ($write as $k_w => $k_v) {
                    $map['writer'] = array('like', '%' . $k_v . '%');
                    $totalPercent += M('work_detail')->where($map)->max('percent');
                }
                $percer = $totalPercent / (100 * $count) * 100;
            } else {
                $map['writer'] = rtrim($row['manager'], ',');
                $percer = M('work_detail')->where($map)->max('percent');
            }
        }

        if ($percer >= 100) {
            $sData['sms_flag'] = 1;
            $sData['total_percent'] = 100;
        } else {
            $sData['sms_flag'] = 0;
            $sData['total_percent'] = $percer ? $percer : 0;
        }

        M('work_plan')->where('plan_id=' . $plan_id)->save($sData);
    }

    //添加进度日志
    public function schedule() {
        if (IS_AJAX) {
            $data = I('post.');
            $dData['percent'] = $data['percent'];
            $dData['progress'] = $data['progress'];
            $dData['plan_id'] = $data['plan_id'];
            $dData['writer'] = session('user_id');
            $dData['write_time'] = date('Y-m-d H:i:s');
            $dData['type_flag'] = 0;
            $dData['uploads'] = $data['uploads'];
            $dData['uploads_url'] = $data['uploads_url'];
            $dData['location'] = '';
            $dData['is_diary'] = $data['is_diary'];

            //去重
            $map['plan_id'] = $data['plan_id'];
            $map['writer'] = session('user_id');
            $map['progress'] = array('like', '%' . $data['progress'] . '%');
            $total = M('work_detail')->where($map)->count();
            if (!$total) {
                $res = M('work_detail')->add($dData);
                unset($map);
                if ($res && $data['is_diary']) {
                    //写入工作日志
                    $lData['user_id'] = session('user_id');
                    $lData['dia_time'] = date('Y-m-d H:i:s');
                    $lData['dia_date'] = date('Y-m-d H:i:s');
                    $lData['dia_type'] = 1;
                    $lData['subject'] = session('user_name') . date('Y-m-d') . '计划日志';
                    $lData['content'] = $data['progress'];
                    $lData['compress_content'] = '(BLOB)' . strlen($data['progress']) . '字节';
                    $lData['is_mobile'] = 1;
                    $res = M('diary')->add($lData);
                }
                if ($res) {
                    //添加阅读者字段（本人）,覆盖原有数据
                    $rData['reader'] = session('user_id');
                    M('work_plan')->where('plan_id=' . $data['plan_id'])->save($rData);

                    //修改总进度字段
                    $this->saveOnePercent($data['plan_id']);

                    //发送提示消息
                    $map['plan_id'] = $data['plan_id'];
                    $row = M('work_plan')->where($map)->find();
                    $content = "和您相关的工作计划《" . $row["name"] . "》新增了一条进度，填写人：" . getChineseName(session('user_id')) . "，填写时间：" . date("Y-m-d H:i:s") . "，<a href=\"http://www.jsumt.com:88/index.php/Index/Plan/show/id/" . $row['plan_id'] . "/webid/" . $this->webid . "\">点击查看</a>";

                    //用户
                    $manager = explode(',', $row['manager']);
                    $paricipator = explode(',', $row['participator']);
                    $creator = explode(',', $row['creator']);
                    $person = explode(',', $row['to_person_id']);
                    $leader = explode(',', $row['opinion_leader']);

                    //部门 
                    $deptUsers = getDeptUsers($row['to_id']);

                    $users = array_merge($manager, $paricipator, $creator, $leader, $person, $deptUsers);
                    $users = array_unique($users);
                    setWeixinMsg($users, $content, $this->webid);

                    $return['info'] = '添加成功';
                    if (isset($_POST['type'])) {
                        $return['url'] = U('show', array('id' => $data['plan_id'], 'type' => I('post.type')));  //返回带参数的详情页
                    } else {
                        $return['url'] = U('show', array('id' => $data['plan_id']));  //返回详情页
                    }
                } else {
                    $return['info'] = '添加失败';
                }
            } else {
                $return['info'] = '请勿重复提交';
            }

            $this->ajaxReturn($return);
        }

        $id = I('id');
        $plan = M('work_plan')->where('plan_id=' . $id)->find();

        $plan['name'] = strlen($plan['name']) > 60 ? msubstr($plan['name'], 0, 20) : $plan['name'];

        $map['plan_id'] = $id;
        $map['writer'] = session('user_id');
        $map['type_flag'] = 0;  //只显示进度
        $info = M('work_detail')->where($map)->order('WRITE_TIME DESC')->select();
//        $total = 0;
//        foreach ($info as $key => $row) {
//            if ($row['percent'] > $info[$key + 1]['percent']) {
//                $total = $row['percent'];
//            } else {
//                $total = $info[$key + 1]['percent'];
//            }
//            //$total += $row['percent'];
//        }
        
        $plan['total'] = M('work_detail')->where($map)->max('percent');
        $plan['info'] = $info;

        $this->is_end = I('is_end');
        $this->plan_id = $id;
        $this->plan = $plan;

        //从当前计划详情页面中打开
        $this->dept = I('get.dept');
        $this->cType = I('get.cType');

        //获取条件参数
        $this->type = I('type');

        $this->display();
    }

    public function comment() {
        $id = I('post.id');
        $content = I('post.content');
        $lng = I('post.lng');
        $lat = I('post.lat');
        $data['plan_id'] = $id;
        $data['write_time'] = date('Y-m-d H:i:s');
        $data['progress'] = $content;
        $data['type_flag'] = 1;
        $data['writer'] = session('user_id');
        $data['location'] = '';

        //去重
        $map['plan_id'] = $id;
        $map['writer'] = session('user_id');
        $map['progress'] = array('like', '%' . $content . '%');
        $total = M('work_detail')->where($map)->count();
        if (!$total) {
            $res = M('work_detail')->add($data);
            unset($map);

            //添加批注提醒
            $map['plan_id'] = $id;
            $row = M('work_plan')->where($map)->find();

            //用户
            $manager = $row['manager'] ? explode(',', $row['manager']) : [];
            $paricipator = $row['participator'] ? explode(',', $row['participator']) : [];
            $creator = $row['creator'] ? explode(',', $row['creator']) : [];
            $person = $row['to_person_id'] ? explode(',', $row['to_person_id']) : [];
            $leader = $row['opinion_leader'] ? explode(',', $row['opinion_leader']) : [];

            //部门 
            $deptUsers = $row['to_id'] ? getDeptUsers($row['to_id']) : [];

            $users = array_merge($manager, $paricipator, $creator, $leader, $person, $deptUsers);
            $users = array_unique($users);
            $content = '和您相关的工作计划《' . $row['name'] . '》新增了一条批注，<a href="http://www.jsumt.com:88/index.php/Index/Plan/show/id/' . $row['plan_id'] . '/webid/' . $this->webid . '">点击查看</a>';

            $res = setWeixinMsg($users, $content, $this->webid);

            if($res['errcode'] == 0){
                $return['status'] = 1;
                $return['msg'] = '提交成功';
                $return['icon'] = 6;
            }else{
                $return['status'] = 0;
                $return['msg'] = '提交失败';
                $return['icon'] = 5;
            }
        } else {
            $return['status'] = 0;
            $return['icon'] = 5;
            $return['msg'] = '请勿重复提交';
        }
        $this->ajaxReturn($return);
    }

    //进度日志删除页
    public function showSchedule() {
        $id = I('id') ? I('id') : session('pcId');

        $map['plan_id'] = $id;
        $info = M('work_plan')->where($map)->find();
        $map['writer'] = array('like', '%' . session('user_id') . '%');
        $info['detail'] = M('work_detail')->where($map)->order('write_time DESC')->select();
        if ($info['detail']) {
            foreach ($info['detail'] as $key => $row) {
                $info['detail'][$key]['formatTime'] = strtotime($row['write_time']);
                $info['detail'][$key]['self'] = session('user_id');     //本人
                //判断当前进度中是否有附件
                if ($row['attachment_name']) {
                    $info['detail'][$key]['file'] = 1;
                    $dUploads = downloadFile($row['attachment_id'], $row['attachment_name'], 'work_plan', $row['uploads'], $row['uploads_url']);
                }
                if ($row['uploads']) {
                    $names = explode(';', rtrim($row['uploads'], ';'));
                    $urls = explode(';', rtrim($row['uploads_url'], ';'));
                    for ($i = 0; $i < count($urls); $i++) {
                        $tmpArr = [];
                        if ($urls[$i]) {
                            if ($dUploads) {
                                $tmpArr['name'] = $names[$i];
                                $tmpArr['url'] = $urls[$i];
                                $info['detail'][$key]['file'] = 1;  //判断是否有附件
                                array_push($dUploads, $tmpArr);
                            } else {
                                $dUploads[$i]['name'] = $names[$i];
                                $dUploads[$i]['url'] = $urls[$i];
                                $info['detail'][$key]['file'] = 1;  //判断是否有附件
                            }
                        }
                    }
                }
            }

            $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
            foreach ($dUploads as $key => $row) {
                $ext = end(explode('.', $row['name']));
                $dUploads[$key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
            }
        }

//        $this->dUploads = $dUploads;
        $this->plan = $info;
        $this->dept = I('dept');
        $this->cType = I('cType');
        $this->display();
    }

    //删除本人进度或批注
    public function delDetail() {
        $id = I('id');
        $row = M('work_detail')->where('detail_id=' . $id)->find();

        //删除移动端附件
        if ($row['uploads_url']) {
            $urls = explode(';', rtrim($row['uploads_url'], ';'));
            foreach ($urls as $url) {
                @unlink('.' . $url);
            }
        }
        //删除PC端附件
        if ($row['attachment_id']) {
            $pcurls = downloadFile($row['attachment_id'], $row['attachment_name'], 'work_plan');
            foreach ($pcurls as $pcurl) {
                @unlink($pcurl['url']);
            }
        }

        $res = M('work_detail')->where('detail_id=' . $id)->delete();
        if ($res !== false) {
            if ($row['type_flag'] == 0) {
                //修改当前计划总进度
                $this->saveOnePercent($row['plan_id']);
            }
            $return['status'] = 1;
            $return['url'] = U('Plan/show', array('id' => $row['plan_id']));
        } else {
            $return['status'] = 0;
        }

        $this->ajaxReturn($return);
    }

    //关注计划
    public function attentPlan() {
        $type = I('type');
        $plan_id = I('plan_id');
        $map['plan_id'] = $plan_id;
        $followUsers = M('work_plan')->field('follow_user')->where($map)->getField('follow_user');

        $flag = 0;
        if ($followUsers) {
            $gzs = array_unique(explode(',', $followUsers));
            if (in_array(session('user_id'), $gzs)) {
                foreach ($gzs as $key => $row) {
                    if (session('user_id') == $row) {
                        unset($gzs[$key]);
                    }
                }
                $content['follow_user'] = implode(',', $gzs);
                $flag = 1;
            } else {
                $content['follow_user'] = $followUsers . session('user_id') . ",";
            }
        } else {
            $content['follow_user'] = session('user_id') . ',';
        }

        $res = M('work_plan')->where($map)->save($content);
        if ($res !== false) {
            $return['status'] = 1;
            $return['msg'] = $flag == 1 ? '已取消' : '已关注';
        } else {
            $return = array('status' => 0, 'msg' => '操作失败');
        }

        $this->ajaxReturn($return);
    }

    //发送提醒
    public function remind() {
        $id = I('id');
        $info = M('work_plan')->where('plan_id=' . $id)->find();

        $users = $info['manager'] ? $info['manager'] : $info['executor'];
        if (strpos($users, ',') !== false) {
            $users = explode(',', rtrim($users, ','));
        }
        $content = '和您相关的计划<a href="http://www.jsumt.com:88/index.php/Index/Plan/show/id/' . $info['plan_id'] . '/webid/' . $this->webid . '">《' . $info['name'] . '》</a>已长时间未填写进展，请尽快提交该计划的进展情况！';
//        var_dump($users);echo '<hr>';echo $content,'<hr/>',$webid;die;
        $res = setWeixinMsg($users, $content, $this->webid);
        if ($res == 0) {
            $return['status'] = 1;
            $data['remind'] = date('Y-m-d');
            M('work_plan')->where('plan_id=' . $id)->save($data);
            $return['remind'] = date('Y-m-d');
            $return['msg'] = '发送成功';
        } else {
            $return['status'] = 0;
            $return['msg'] = '发送失败';
        }

        $this->ajaxReturn($return);
    }
    
    //计划设置
    public function setPlan(){
        $this->cates = M('plan_type')->where('pid = 0')->order('pid')->select();
        $this->cateCount = count($this->cates);
        
        //获取标记
        $this->childs = M('plan_type')->where('pid != 0')->order('user_id')->select();
        $this->display();
    }

}
